<template>
  <!-- 攻城狮  工程师 -->
 
  <div class="cart">
  <van-nav-bar
  title="购物车"
  left-text="返回"
  right-text="首页"
  left-arrow
  @click-left="onClickLeft"
  @click-right="onClickRight"
/>
    <div class="good-list" v-if="list.length > 0">
      <div class="goods" v-for="data in list" :key="data._id">
        <van-checkbox class="checkbox" v-model="data.checked"
          >复选框</van-checkbox
        >
        <img class="goods-img" :src="data.product.coverImg" alt="" />
        <div class="goods-info">
          <p>{{ data.product.name }}</p>
          <span>￥{{ data.product.price }}</span>
          <span @click="updatePro(data.product._id, 1)">+</span>
          {{ data.quantity }}
          <span @click="data.quantity > 1 && updatePro(data.product._id, -1)"
            >-</span>
          <van-icon
            name="delete-o"
            v-show="data.checked"
            @click="del(data._id)"
          />
        </div>
      </div>
    </div>
    <div v-else>购物车空空如也</div>
    <!-- 全选 -->
    <van-submit-bar
      :price="sumPrice * 100"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox v-model="checked" />
      <span>全选</span>
      <van-icon name="delete-o" @click="dels" />
    </van-submit-bar>
  </div>
</template>

<script>
import {
  reqCartlist,
  addtocart,
  reqDeleteCart,
  reqDeleteCarts,
} from "../../api/cart";
import { Toast } from 'vant';
import { addorder } from "@/api/order";
import { getaddress, getaddresses } from "@/api/address";
export default {
  data() {
    return {
      list: [],
    };
  },
  // 计算属性
  // $set vue中添加动态属性
  computed: {
    checked: {
      // 用于设置全选全不选
      set(flag) {
        console.log(flag);
        this.list.map((item) => this.$set(item, "checked", flag));
      },
      get() {
        // 购物车的长度被删除完了，变成0了
        if (this.list.length == 0) {
          return false;
        } else {
          return (
            this.list.length === this.list.filter((item) => item.checked).length
          );
        }
      },
    },
    // 返回选中的项
    selectgoods() {
      let selectList = [];
      this.list.filter((item) => {
        if (item.checked) {
          selectList.push(item._id);
        }
      });
      return selectList;
    },
    //返回选中的商品
    selectproduct() {
      let plist = [];
      this.list.filter((item) => {
        if (item.checked) {
          plist.push({
            quantity: item.quantity,
            product: item.product._id,
            price: item.product.price,
          });
        }
      });
      return plist;
    },
    // 计算总价
    sumPrice() {
      // reduce来实现求和
      return this.list
        .filter((item) => {
          return item.checked;
        })
        .reduce(function (pre, cur) {
          return (pre += cur.product.price * cur.quantity);
        }, 0);
    },
  },
  watch: {},

  methods: {
    async initCart() {
      const result = await reqCartlist();
      // console.log(result);
      this.list = result;
    },
    // 添加减少购物车
    async updatePro(id, num = 1) {
      const result = await addtocart({
        product: id,
        quantity: num,
      });
      // console.log("121212", result);
      // 下面的操作一定要发生在添加或者删除成功之后的回调中
      // 客户端操作
      this.list.forEach((data) => {
        if (data.product._id == id) {
          data.quantity = data.quantity + num;
        }
      });
    },
    // 根据id删除单个购物车数据
    async del(id) {
      const result = await reqDeleteCart(id);
      // console.log("删除", result);
    },
    // 批量删除
    async dels() {
      // ids数据从哪来？
      const result = await reqDeleteCarts(this.selectgoods);
      // console.log("12121212", result);
      this.initCart();
    },
    // 获取单个收货地址
    async onaddress(){
      const result = await getaddress();
      console.log(result);
      let addArr={};
      result.addresses.forEach((item)=>{
        addArr={
          ...item,
        };
      });
    this.$router.commit("address/savereceiver",addArr.receiver);
    this.$router.commit("address/savemobile",addArr.mobile);
    this.$router.commit("address/saveregiions",addArr.regions);
    },
    
    // 提交订单
   async onSubmit() {
      // 查看有没有收货人信息，没有跳转到添加收货人页面
      const receiver = this.$store.state.address.receiver;
      const regions = this.$store.state.address.regions;
      const address = this.$store.state.address.address;
      if (receiver && regions && address) {
        // 所有信息都存在的话，跳转到订单页面
        const result = await addorder({
          receiver,
          regions,
          address,
          orderDetails:this.selectproduct,
        });
        
        if(result.code == "success"){
          Toast.success(result.message);
          setTimeout(()=>{
            this.$router.push("/order");
          },1000);
        }else{
          Toast.fail(result.message)
        }
      }else {
        // 只要有一个不存在，就跳转到添加收货人信息页面
        this.$router.push("/address");
        Toast('请添加收货人');
      }
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    onClickRight() {
      this.$router.push("/home");
    },
  },
  created() {
    this.initCart();
  },
  mounted() {},
  components: {},
};
</script>
<style scoped>
.good-list {
  padding-bottom: 50px;
}
.goods {
  display: flex;
  height: 100px;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 15px;
}
.checkbox {
  width: 20px;
  height: 20px;
}
.goods-img {
  width: 80px;
  height: 80px;
}
.goods-info {
  flex: 1;
  padding-left: 10px;
}
.goods-info span:nth-of-type(2){
  margin-left: 10px;
}
</style>
